package gang.com.downloader;

import gang.com.downloader.DownloadEntry.DownloadStatus;

/**
 * Created by xiaogangzai on 2017/11/4.
 */

public class DownloadTask implements Runnable{

    private final DownloadEntry entry;
    private boolean isPause;
    private boolean isCancle;
    public DownloadTask(DownloadEntry entry) {
        this.entry = entry;
    }

    public void pause() {
        Trace.e("download paused");
        isPause = true;
    }

    public void cancle() {
        isCancle = true;
    }

    public void start() {
        entry.status = DownloadStatus.downloading;
        //更新状态，这里要通知我们的上层也就是观察者，告诉用户别再点了已经开始下载了
        //调用被观察者中的方法
        DataChanger.getmInstance().postStatus(entry);
        entry.totalLength = 1024 * 5;
        for (int i = 0; i < entry.totalLength; ) {
            if (isPause || isCancle){
                entry.status = isPause ? DownloadEntry.DownloadStatus.paused : DownloadEntry.DownloadStatus.cancelled;

//                TODO if cancelled, delete related file
                return;
            }


            i += 1024;
            entry.currentLength += 1024;
            DataChanger.getmInstance().postStatus(entry);
        }
        entry.status = DownloadStatus.completed;
        DataChanger.getmInstance().postStatus(entry);
    }

    @Override
    public void run() {
        start();
    }
    // TODO check if support range,单线程还是多线程
}
